package org.sunrise.game.game.logic.map;

import com.google.protobuf.Message;
import org.sunrise.game.game.human.HumanObject;
import org.sunrise.game.game.modules.MapModule;
import org.sunrise.game.game.proto.MapProto;
import org.sunrise.game.game.proto.TopicProto;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GameMap {

    private final int mapId;
    private final Map<String, HumanObject> humanObjectMap = new ConcurrentHashMap<>();

    public GameMap(int mapId) {
        this.mapId = mapId;
    }

    // 玩家进入地图
    public void humanObjectEnter(HumanObject humanObject) {
        // 把自己的信息同步给其他人
        MapModule module = humanObject.getModule(MapModule.class);
        var syncBuilder = MapProto.MS2C_Sync.newBuilder();
        MapProto.STRoleInfo roleInfo = MapProto.STRoleInfo.newBuilder()
                .setHumanId(humanObject.getHumanId())
                .setName(humanObject.getConnectObject().getUid())
                .setMapPostX(module.getMapPostX())
                .setMapPostY(module.getMapPostY())
                .setMapPostZ(module.getMapPostZ())
                .build();
        syncBuilder.addRoles(roleInfo);
        broadcastToAll(TopicProto.TOPIC.TOPIC_TYPE_MAP_VALUE, MapProto.FROM_SERVER.S2C_Enter_VALUE, syncBuilder);

        module.setMapId(mapId);
        humanObjectMap.put(humanObject.getHumanId(), humanObject);
    }

    // 玩家离开地图
    public void humanObjectLeave(String humanId) {
        HumanObject humanObject = humanObjectMap.get(humanId);
        if (humanObject == null) {
            return;
        }
        var leaveMessage = MapProto.MS2C_Leave.newBuilder().setHumanId(humanObject.getHumanId());
        broadcastToAll(TopicProto.TOPIC.TOPIC_TYPE_MAP_VALUE, MapProto.FROM_SERVER.S2C_Leave_VALUE, leaveMessage);

        humanObject.getModule(MapModule.class).setMapId(0);
        humanObjectMap.remove(humanId);
    }

    // 广播给地图中所有玩家
    public void broadcastToAll(int packetType, int packetId, Message.Builder builder) {
        for (HumanObject humanObject : humanObjectMap.values()) {
            humanObject.sendMsg(packetType, packetId, builder);
        }
    }

    // 广播地图中的玩家信息
    public void sync(HumanObject humanObject) {
        var syncBuilder = MapProto.MS2C_Sync.newBuilder();
        for (HumanObject ho : humanObjectMap.values()) {
            MapModule module = ho.getModule(MapModule.class);
            MapProto.STRoleInfo roleInfo = MapProto.STRoleInfo.newBuilder()
                    .setHumanId(ho.getHumanId())
                    .setName(ho.getConnectObject().getUid())
                    .setMapPostX(module.getMapPostX())
                    .setMapPostY(module.getMapPostY())
                    .setMapPostZ(module.getMapPostZ())
                    .build();
            syncBuilder.addRoles(roleInfo);
        }
        humanObject.sendMsg(TopicProto.TOPIC.TOPIC_TYPE_MAP_VALUE, MapProto.FROM_SERVER.S2C_Sync_VALUE, syncBuilder);
    }
}
